package com.yff.activity.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yff.activity.service.ITestService;
import com.yff.system.dubbo.api.DemoService;
import com.yff.system.dubbo.api.GreetingProviderService;
import com.yff.system.dubbo.api.dto.TestDTO;
import com.yff.system.dubbo.api.vo.TestVO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class ITestServiceImpl implements ITestService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(providedBy = "provider-yff-system")
    private GreetingProviderService greetingProviderService;

    @DubboReference(providedBy = "provider-yff-system")
    private DemoService demoService;

    @SentinelResource(value = "testRpc", blockHandler = "testRpcBlockHandler", fallback = "testRpcFallback")
    @Override
    public String testRpc(String username) {
        TestDTO dto = new TestDTO();
        dto.setId(10086);
        TestVO vo = greetingProviderService.testRpc(dto);
        logger.info("greetingProviderService.testRpc : id {}",vo.getId());
        String data = demoService.helloDemo();
        logger.info("demoService.helloDemo : {} {}",username,data);
        return "success" + vo.getId();
    }

    // 服务流量控制处理，参数最后多一个 BlockException，其余与原函数一致。
    public String testRpcBlockHandler(String username, BlockException ex)
    {
        logger.debug("selectUserByNameBlockHandler异常信息："+ ex.getMessage());
        return "{\"code\":\"500\",\"msg\": \"" + username + "服务流量控制处理\"}";
    }

    // 服务熔断降级处理，函数签名与原函数一致或加一个 Throwable 类型的参数
    public String testRpcFallback(String username, Throwable throwable)
    {
        logger.debug("selectUserByNameFallback异常信息：" + throwable.getMessage());
        return "{\"code\":\"500\",\"msg\": \"" + username + "服务熔断降级处理\"}";
    }
}
